// ignore_for_file: non_constant_identifier_names

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';

/// 计算公式：实际尺寸 = UI尺寸 * 设备宽度/设计图宽度
/// 适配尺寸类
class CNMScreenUtils {
  static MediaQueryData? _mediaQueryData;

  /// 实际设备宽度 / 设计图宽度比例
  static double _scaleWidth = 0;

  /// 实际设备高度 / 设计图高度比例
  static double _scaleHeight = 0;

  /// 文本、圆角比例 16 * CNMScreenUtils.scaleText
  static double scaleText = 0;

  /// 设备的宽度
  static double screenWidth = 0;

  /// 设备的高度
  static double screenHeight = 0;

  /// 设备顶部安全距离
  static double topSafe = 0;

  /// 设备底部安全距离
  static double bottomSafe = 0;

  /// 是否具有刘海屏
  static bool isFullScreen = false;

  /// 导航栏高度
  static double get navBarHeight => kToolbarHeight + topSafe;

  /// 初始化
  static void cnm_init(
    BuildContext context, {
    double? designWidth,
    double? designHeight,
  }) {
    double dw = designWidth ?? (Platform.isAndroid ? 720 : 375);
    double dh = designHeight ?? (Platform.isAndroid ? 1080 : 812);

    _mediaQueryData = MediaQuery.of(context);

    screenWidth = _mediaQueryData!.size.width;
    screenHeight = _mediaQueryData!.size.height;
    topSafe = _mediaQueryData!.padding.top;
    bottomSafe = _mediaQueryData!.padding.bottom;
    isFullScreen = bottomSafe > 0;
    _scaleWidth = screenWidth / dw;
    _scaleHeight = screenHeight / dh;

    scaleText = min(_scaleWidth, _scaleHeight);
  }

  /// 获取实际宽度
  static double cnm_getPracticalWidth(num inputWidth) => inputWidth * _scaleWidth;

  /// 获取实际高度
  static double cnm_getPracticalHeight(num inputHeight) => inputHeight * _scaleHeight;
}

/// 对 num 进行扩展
/// 对num进行扩展，可直接使用1.2.w的形式代替cnm_getPracticalWidth(1.2)
extension CNMNumExtension on num {
  /// 宽度
  double get w => CNMScreenUtils.cnm_getPracticalWidth(this);

  /// 高度
  double get h => CNMScreenUtils.cnm_getPracticalHeight(this);

  /// 圆角  16.sp
  double get sp => CNMScreenUtils.scaleText * this;

  /// 圆角  10.r
  double get r => CNMScreenUtils.scaleText * this;
}
